"use strict";
/**
 * @name battleSign
 * 战令系统
 */

/**
 * @name initBattleSign
 * 初始化战令
 */
exports.initBattleSign = async function () {
    this.updater.role.key("battleSign");
    await this.updater.data();
    let battleSignInfo = this.updater.role.get("battleSign")
    // 检查战令是否在开放时间内
    const now = Date.now();
    // const battleConfig = this.config('battlePassID');
    // if (!battleConfig) {
    //     return this.quick_error("M2PTA51", "战令数据未找到");
    // }
    const battlePassConfig = this.config("battlePassconfig", 0);
    if (!battlePassConfig) {
        return this.quick_error("M2PTA51", "战令数据未找到");
    }
    // let battlePassConfig;
    // for (let key in battlePassConfigAll) {
    //     battlePassConfig = battlePassConfigAll[key];
    //     break;
    // }

    // let id = 0;
    // for (let k in battleConfig) {
    const beginDate = new Date(battlePassConfig.startTime).getTime();
    const endDate = new Date(battlePassConfig.endTime).getTime();
    if (now < beginDate || now > endDate) {
        return this.quick_error("M2PTA51", "不在战令开放时间内");
    }
    // // 检查之前的战令奖励是否已经完全领取
    // if (battleSignInfo.freeReward < battleSignInfo.level || battleSignInfo.payReward < battleSignInfo.level) {
    //     return this.quick_error("M2PTA51", "之前的战令奖励未完全领取");
    // }
    //判断id是否匹配
    if (battleSignInfo.bTime != beginDate) {
        // id = battlePassConfig.battlePassID;
        battleSignInfo.bTime = beginDate;
        battleSignInfo.eTime = endDate;
        battleSignInfo.buyFlag = 0;
        battleSignInfo.level = 0;
        battleSignInfo.exp = 0; // 重置经验
        battleSignInfo.freeReward = 0; // 重置免费奖励领取状态
        battleSignInfo.payReward = 0; // 重置付费奖励领取状态
    } else {
        return this.quick_error("M2PTA51", "不能重复初始化战令");
    }
    // }
    // if (id == 0) {
    //     return this.quick_error("M2PTA51", "没有战令开放");
    // }
    this.updater.role.set('battleSign', battleSignInfo);
    return this.updater.save();
}


/**
 * @name dailyProcess
 *@param string idList 任务下标串,以","分割
 * 战令每日任务进度领奖
 */
exports.dailyProcess = async function () {
    // const id = this.get('id', 'int');
    // if (!id) {
    //     return this.quick_error('M2saghge140', '参数错误');
    // }
    const arg = this.get('idList', 'string').trim();
    if (!arg) {
        return this.quick_error('M2saghge140', '必须有消耗品');
    }
    let idList = arg.split(",");
    let idMap = new Map();
    for (let id of idList) {
        if (idMap.has(id)) {
            return this.quick_error('M2saghge140', 'ID重复,领取失败');
        }
        idMap.set(id, 1);
    }
    // const id = this.get('id', 'string');
    // if (!id) {
    //     return this.quick_error('M2saghge140', '参数错误');
    // }
    const battlePassConfig = this.config("battlePassconfig", 0);
    if (!battlePassConfig) {
        return this.quick_error("M2PTA51", "战令数据未找到");
    }
    this.updater.daily.key("todayBattleSignTask");
    this.updater.daily.key("dailyBattleSignProcess");
    this.updater.role.key("battleSign");
    await this.updater.data();
    let battleSignInfo = this.updater.role.get("battleSign")
    let dailyProcess = this.updater.daily.get("dailyBattleSignProcess") || [];
    // let todayTask = this.updater.daily.get("todayTask") || [];
    let addExp = 0;
    let weekAdd = await this.updater.daily.model.week("record.72");;
    for (let id of idList) {
        for (let i in dailyProcess) {
            if (dailyProcess[i] == id) {
                return this.quick_error("M2PTA51", "任务已经领取过了");
            }
        }
        let taskConfig = this.config("battlePassDailyTask", id);
        if (!taskConfig) {
            return this.quick_error("M2PTA51", "配置不存在");
        }
        await this.library.call(this.updater, "valuesNew", taskConfig['tar'], taskConfig['key'].toString()).then(val => {
            if ((taskConfig['compare'] > 0 && val > taskConfig['val']) || (taskConfig['compare'] <= 0 && val < taskConfig['val'])) {
                return this.quick_error("M2PTA111", 'task_val_limit', val, taskConfig['val'], taskConfig['compare']);
            }
            if ((taskConfig['score'] + addExp + weekAdd['record.72']) > battlePassConfig.weekExpLimit) {
                battleSignInfo.exp += (taskConfig['score'] - ((taskConfig['score'] + addExp + weekAdd['record.72']) - battlePassConfig.weekExpLimit));
                addExp += (taskConfig['score'] - ((taskConfig['score'] + addExp + weekAdd['record.72']) - battlePassConfig.weekExpLimit));
            } else {
                battleSignInfo.exp += taskConfig['score'];
                addExp += taskConfig['score'];
            }
            // battleSignInfo.exp += taskConfig['score'];
        });
        dailyProcess.push(id);
    }
    // if (!addExp) {
    //     return this.quick_error("M2PTA51", "经验已达每周上限");
    // }
    //判断是否升级
    let battleSignConfig = this.config("battlePassReward");
    let upLevel = 0;
    const maxLevel = Object.keys(battleSignConfig).length;
    for (let i = battleSignInfo.level + 1; i <= maxLevel; i++) {
        if ((battleSignInfo.exp - battleSignConfig[i].levelExp) >= 0) {
            battleSignInfo.exp -= battleSignConfig[i].levelExp
            upLevel++;
        }
    }
    battleSignInfo.level += upLevel;
    if (battleSignInfo.level > maxLevel) {
        battleSignInfo.level = maxLevel;
    }
    this.updater.daily.add("record.72", addExp);
    this.updater.record.add("72", addExp);
    this.updater.daily.set("dailyBattleSignProcess", dailyProcess);
    this.updater.role.set('battleSign.exp', battleSignInfo.exp);
    this.updater.role.set('battleSign.level', battleSignInfo.level);
    return this.updater.save();
}

/**
 * @name week
 * @param string idList 任务下标串,以","分割
 * 战令每周任务领奖
 */
exports.week = async function () {
    const arg = this.get('idList', 'string').trim();
    if (!arg) {
        return this.quick_error('M2saghge140', '必须有消耗品');
    }
    let idList = arg.split(",");
    let idMap = new Map();
    for (let id of idList) {
        if (idMap.has(id)) {
            return this.quick_error('M2saghge140', 'ID重复,领取失败');
        }
        idMap.set(id, 1);
    }
    //taskWeek
    this.updater.role.key("taskBattleSignWeek");
    this.updater.role.key("battleSign");
    await this.updater.data();
    let battleSignInfo = this.updater.role.get("battleSign")
    let _taskWeek = this.updater.role.get("taskBattleSignWeek") || { 'id': 0, 'task': [] };
    let _weekCuo = this.library("time/week");
    if (_weekCuo != _taskWeek.id) {
        _taskWeek.id = _weekCuo;
        _taskWeek.task = [];
    }
    const battlePassConfig = this.config("battlePassconfig", 0);
    if (!battlePassConfig) {
        return this.quick_error("M2PTA51", "战令数据未找到");
    }
    // let _task = _taskWeek.task;
    let addExp = 0;
    let weekAdd = await this.updater.daily.model.week("record.72");;
    for (let id of idList) {
        // if(parseInt(i) > _taskWeek.task.length){
        //     continue;
        // }
        // let id = _taskWeek.task[parseInt(i)].id;
        let taskConfig = this.config("battlePassWeekTask", id);
        if (!taskConfig) {
            return this.quick_error("M2PTA51", "配置不存在");
        }
        if ((weekAdd['record.72'] + addExp) > battlePassConfig.weekExpLimit) {
            break;
        }
        await this.library.call(this.updater, "valuesNew", taskConfig['tar'], taskConfig['key'])
            .then(val => {
                if ((taskConfig['compare'] > 0 && val > taskConfig['val']) || (taskConfig['compare'] <= 0 && val < taskConfig['val'])) {
                    return this.quick_error("M2PTA111", 'task_val_limit', val, taskConfig['val'], taskConfig['compare']);
                }


                if (_taskWeek.task.indexOf(id) >= 0) {
                    return this.quick_error("M2PTA53", "已经领取过了");
                }
                if ((taskConfig['score'] + addExp + weekAdd['record.72']) > battlePassConfig.weekExpLimit) {
                    battleSignInfo.exp += (taskConfig['score'] - ((taskConfig['score'] + addExp + weekAdd['record.72']) - battlePassConfig.weekExpLimit));
                    addExp += (taskConfig['score'] - ((taskConfig['score'] + addExp + weekAdd['record.72']) - battlePassConfig.weekExpLimit));
                } else {
                    battleSignInfo.exp += taskConfig['score'];
                    addExp += taskConfig['score'];
                }
                _taskWeek.task.push(id);
                // this.updater.role.set("taskBattleSignWeek", _taskWeek);
                // if(taskConfig.dtype===0){
                //     //普通任务
                //     //成交 活跃度任务完成数量
                //     this.updater.record.add(93136,1);
                //     this.updater.daily.add('dtaskN',1);
                // }
                // //累计每日任务完成数量
                // if (taskConfig['dtype'] === 0) {
                //     // this.updater.record.add("activeRequire",taskConfig['active']);
                //     this.updater.daily.add("record." + "57", taskConfig['active']);
                // }
                // return this.updater.save();
                // return this.updater.data().then(() => {
                // });
            })
    }
    // if (!addExp) {
    //     return this.quick_error("M2PTA51", "经验已达每周上限");
    // }
    let battleSignConfig = this.config("battlePassReward");
    let upLevel = 0;
    const maxLevel = Object.keys(battleSignConfig).length;
    for (let i = battleSignInfo.level + 1; i <= maxLevel; i++) {
        if ((battleSignInfo.exp - battleSignConfig[i].levelExp) >= 0) {
            battleSignInfo.exp -= battleSignConfig[i].levelExp
            upLevel++;
        }
    }
    battleSignInfo.level += upLevel;
    if (battleSignInfo.level > maxLevel) {
        battleSignInfo.level = maxLevel;
    }
    this.updater.daily.add("record.72", addExp);
    this.updater.record.add("72", addExp);
    this.updater.role.set("taskBattleSignWeek", _taskWeek);
    this.updater.role.set('battleSign.exp', battleSignInfo.exp);
    this.updater.role.set('battleSign.level', battleSignInfo.level);
    return this.updater.save();
}

/**
 * @name buyLevel
 * @param int num
 * 购买战令等级
 */
exports.buyLevel = async function () {
    let num = this.get('num', 'int');
    if (!num) {
        return this.quick_error('M2saghge140', '参数错误', num);
    }
    this.updater.role   .key("battleSign");
    await this.updater.data();
    const battleSignInfo = this.updater.role.get("battleSign")
    const battlePassConfig = this.config("battlePassconfig", 0);
    if (!battlePassConfig) {
        return this.quick_error("M2PTA51", "战令数据未找到");
    }
    this.updater.item.sub(battlePassConfig.purchaseItem, battlePassConfig.purchaseNum * num);
    this.updater.role.set('battleSign.level', battleSignInfo.level + num);
    return this.updater.save();
}

/**
 * @name battleSignTask
 *@param string idList 任务下标串,以","分割
 * 战令赛季任务进度领奖
 */
exports.battleSignTask = async function () {
    const arg = this.get('idList', 'string').trim();
    if (!arg) {
        return this.quick_error('M2saghge140', '必须有消耗品');
    }
    let idList = arg.split(",");
    let idMap = new Map();
    for (let id of idList) {
        if (idMap.has(id)) {
            return this.quick_error('M2saghge140', 'ID重复,领取失败');
        }
        idMap.set(id, 1);
    }
    this.updater.role.key("battleSignTask");
    this.updater.role.key("battleSign");
    await this.updater.data();
    let battleSignInfo = this.updater.role.get("battleSign")
    let _taskWeek = this.updater.role.get("battleSignTask") || { 'id': 0, 'task': [] };
    if (battleSignInfo.bTime != _taskWeek.id) {
        _taskWeek.id = battleSignInfo.bTime;
        _taskWeek.task = [];
    }
    const battleConfig = this.config('battlePassconfig', 0);
    if (!battleConfig) {
        return this.quick_error("M2PTA51", "战令数据未找到");
    }
    const beginDate = new Date(battleConfig.startTime).getTime();
    const endDate = new Date(battleConfig.endTime).getTime();
    let taskConfig = this.config("battlePassTask");
    if (!taskConfig) {
        return this.quick_error("M2PTA51", "配置不存在");
    }
    for (let id of idList) {
        if (!taskConfig[id]) {
            return this.quick_error("M2PTA51", "配置任务不存在");
        }
        // for (let k in taskConfig.Coll) {
        // if (parseInt(id) == taskConfig.id) {
        await this.library.call(this.updater, "valuesNew", taskConfig[id]['tar'], taskConfig[id]['key'], beginDate, endDate)
            .then(val => {
                if ((taskConfig[id]['compare'] > 0 && val > taskConfig[id]['val']) || (taskConfig[id]['compare'] <= 0 && val < taskConfig[id]['val'])) {
                    return this.quick_error("M2PTA111", 'task_val_limit', val, taskConfig[id]['val'], taskConfig[id]['compare']);
                }
                battleSignInfo.exp += taskConfig[id]['score'];
                if (_taskWeek.task.indexOf(id) >= 0) {
                    return this.quick_error("M2PTA53", "已经领取过了");
                }
                _taskWeek.task.push(id);
                // this.updater.role.set("battleSignTask", _taskWeek);
            })
        // }
        // }
    }
    let battleSignConfig = this.config("battlePassReward");
    let upLevel = 0;
    const maxLevel = Object.keys(battleSignConfig).length;
    for (let i = battleSignInfo.level; i < maxLevel; i++) {
        if ((battleSignInfo.exp - battleSignConfig[i].levelExp) >= 0) {
            battleSignInfo.exp -= battleSignConfig[i].levelExp
            upLevel++;
        }
    }
    battleSignInfo.level += upLevel;
    if (battleSignInfo.level > maxLevel) {
        battleSignInfo.level = maxLevel;
    }
    this.updater.role.set("battleSignTask", _taskWeek);
    this.updater.role.set('battleSign.exp', battleSignInfo.exp);
    this.updater.role.set('battleSign.level', battleSignInfo.level);
    return this.updater.save();
}



/**
 * @name getReward
 * @param int level
 * 领取战令奖励
 */
exports.getReward = async function () {
    let num = this.get('level', 'int');
    if (!num) {
        return this.quick_error('M2saghge140', '参数错误', num);
    }
    this.updater.role.key("battleSign");
    await this.updater.data();
    const battleSignInfo = this.updater.role.get("battleSign")
    const battleSignConfig = this.config("battlePassReward");
    const maxLevel = Object.keys(battleSignConfig).length;
    let reward = {}
    for (let i = battleSignInfo.freeReward + 1; i <= battleSignInfo.level; i++) {
        if (i > num) {
            break;
        }
        for (let k in battleSignConfig[i].itemDrop) {
            if (reward.hasOwnProperty(battleSignConfig[i].itemDrop[k].id)) {
                reward[battleSignConfig[i].itemDrop[k].id] += battleSignConfig[i].itemDrop[k].num;
            } else {
                reward[battleSignConfig[i].itemDrop[k].id] = battleSignConfig[i].itemDrop[k].num;
            }
            // this.updater.add(battleSignConfig[i].itemDrop[k].id, battleSignConfig[i].itemDrop[k].num);
        }
    }
    if (battleSignInfo.buyFlag) {
        for (let i = battleSignInfo.payReward + 1; i <= battleSignInfo.level; i++) {
            if (i > num) {
                break;
            }
            for (let k in battleSignConfig[i].rareItemDrop) {
                if (reward.hasOwnProperty(battleSignConfig[i].rareItemDrop[k].id)) {
                    reward[battleSignConfig[i].rareItemDrop[k].id] += battleSignConfig[i].rareItemDrop[k].num;
                } else {
                    reward[battleSignConfig[i].rareItemDrop[k].id] = battleSignConfig[i].rareItemDrop[k].num;
                }
                // this.updater.add(battleSignConfig[i].rareItemDrop[k].id, battleSignConfig[i].rareItemDrop[k].num);
            }
        }
        this.updater.role.set('battleSign.payReward', battleSignInfo.level);
    }
    for (let key in reward) {
        this.updater.add(parseInt(key), reward[key]);
    }
    this.updater.role.set('battleSign.freeReward', battleSignInfo.level);
    return this.updater.save();
}


// function checkTime(id) {
//     const battleConfig = this.config('battlePassID', id);
//     if (!battleConfig) {
//         return this.quick_error("M2PTA51", "战令数据未找到");
//     }
//     const beginDate = new Date(battleConfig.startTime).getTime();
//     const endDate = new Date(battleConfig.endTime).getTime();
//     if (now < beginDate || now > endDate) {
//         return this.quick_error("M2PTA51", "不在战令开放时间内");
//     }
//     return true;
// }


// /**
//  * @name buyBattleSign
//  * @param int id 战令id
//  * 购买战令
//  */
// exports.buyBattleSign = async function () {
//     const id = this.get('id', 'int');
//     if (!id) {
//         return this.quick_error('M2saghge140', '参数错误');
//     }
//     // this.updater.daily.key("battleSign");
//     this.updater.role.key("battleSign");
//     await this.updater.data();
//     let battleSignInfo = this.updater.role.get("battleSign")
//     // 检查战令是否在开放时间内
//     const now = Date.now();
//     const battlePassConfig = this.config("BattlePass", id);
//     if (!battlePassConfig) {
//         return this.quick_error("M2PTA51", "战令数据未找到");
//     }
//     const battleConfig = this.config('battlePassID', battlePassConfig.battlePassID);
//     if (!battleConfig) {
//         return this.quick_error("M2PTA51", "战令数据未找到");
//     }
//     const beginDate = new Date(battleConfig.startTime).getTime();
//     const endDate = new Date(battleConfig.endTime).getTime();
//     if (now < beginDate || now > endDate) {
//         return this.quick_error("M2PTA51", "不在战令开放时间内");
//     }
//     // // 检查之前的战令奖励是否已经完全领取
//     // if (battleSignInfo.freeReward < battleSignInfo.level || battleSignInfo.payReward < battleSignInfo.level) {
//     //     return this.quick_error("M2PTA51", "之前的战令奖励未完全领取");
//     // }
//     //判断id是否匹配
//     if (battlePassConfig.battlePassID != battleSignInfo.ID) {
//         battleSignInfo.buyFlag = 0;
//         battleSignInfo.level = 0;
//         battleSignInfo.exp = 0; // 重置经验
//         battleSignInfo.freeReward = 0; // 重置免费奖励领取状态
//         battleSignInfo.payReward = 0; // 重置付费奖励领取状态
//     }
//     //购买消耗
//     this.updater.sub(id, 1);
//     //购买时额外给的东西
//     const rewardConfig = this.config("battlePassUnLockReward", battlePassConfig.battlePassID);
//     //给基础奖励
//     if (battleSignInfo.buyFlag == 0) {
//         for (let i = 0; i < rewardConfig.basicItemDrop.length; i++) {
//             this.updater.add(rewardConfig.basicItemDrop[i].id, rewardConfig.basicItemDrop[i].num);
//         }
//     }
//     // 更新角色的战令数据
//     battleSignInfo.ID = battlePassConfig.battlePassID;
//     if (battlePassConfig.levelUp) {
//         battleSignInfo.buyFlag = 2;  // 设置为已购买,0 免费,1 基础版，2 豪华版
//         //给豪华奖励
//         for (let i = 0; i < rewardConfig.richItemDrop.length; i++) {
//             this.updater.add(rewardConfig.richItemDrop[i].id, rewardConfig.richItemDrop[i].num);
//         }
//     } else {
//         battleSignInfo.buyFlag = 1;  // 设置为已购买,0 免费,1 基础版，2 豪华版
//     }
//     battleSignInfo.level += battlePassConfig.levelUp; // 重置等级
//     this.updater.role.set('battleSign', battleSignInfo);
//     return this.updater.save();
// }
